﻿using SqlSugar;
using System;
using System.Data;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Cap.Services.Manager.Models;

namespace Cap.Services.Manager
{
    public class TestServices : ITestServices
    {
        SqlSugarClient db;
        private readonly ICapPublisher _capBus;
        public TestServices(ICapPublisher capPublisher)
        {
            db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "Data Source=localhost;initial Catalog=userdb;User ID=root;Password=123456",
                DbType = SqlSugar.DbType.MySql,//设置数据库类型
                IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
                InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
            });
            _capBus = capPublisher;
        }

        public async Task<string> Query(int id)
        {
            return (await db.Queryable<User>().Where(c => c.ID == id).FirstAsync())?.UserName;
        }

        public async Task Insert()
        {
            //插入用户
            var data = new User()
            {
                UserName = "小谢",
                FK_Company = 1,
                CooperateType = 1,
                Phone = "18146706943",
                Pwd = "123456",
                Status = 1,
                IsVaild = "T",
                CreateTime = DateTime.Now,
                CreateUser = 1
            };
            var primaryKey = await db.Insertable(data).ExecuteCommandAsync();
            //插入角色
            var userole = new UserRole()
            {
                FK_Role = 1,
                FK_User = primaryKey,
                IsVaild = "T",
                CreateUser = 1,
                CreateDate = DateTime.Now,
            };
            await db.Insertable(userole).ExecuteCommandAsync();
            Console.WriteLine("----- 插入成功！----");
            _capBus.Publish("sample.rabbitmq.MysqlServer", $"推送时间： {DateTime.Now.ToString()}");
        }


        /// <summary>
        /// 中转
        /// </summary>
        /// <returns></returns>
        public async Task Transfer()
        {
            await PublistMsg();
        }

        public async Task PublistMsg()
        {
            await Task.Run(() =>
            {
                _capBus.Publish("Transfer.rabbitmq.test", $"测试中转的需要打请求方式吗， 推送时间： {DateTime.Now.ToString()}");
            });

        }

    }
}
